package com.spring.boot.core.event;

import java.util.List;
import java.util.concurrent.ConcurrentMap;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

public class EventDispatcher {

	private static ConcurrentMap<Class<? extends Event>, List<EventListener>> listeners = Maps.newConcurrentMap();

	public static synchronized void registerListener(EventListener listener, Class<? extends Event> c) {
		List<EventListener> listenerList = listeners.get(c);
		if (listenerList == null) {
			listenerList = Lists.newCopyOnWriteArrayList();
			listeners.put(c, listenerList);
		}
		listenerList.add(listener);
	}

	public static synchronized void removeListener(EventListener listener, Class<? extends Event> c) {
		List<EventListener> listenerList = listeners.get(c);
		if (listenerList != null) {
			listenerList.remove(listener);
		}
	}

	public static synchronized void removeListeners(Class<? extends Event> c) {
		listeners.remove(c);
	}

	public static synchronized void removeAllListeners() {
		listeners.clear();
	}

	public static void sendEvent(Event e) {
		List<EventListener> listenerList = listeners.get(e.getClass());
		if (listenerList != null) {
			for (EventListener listener : listenerList) {
				listener.onReceiveEvent(e);
			}
		}
	}
}
